﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Client.Test
{
    /// <summary>
    /// Interaction logic for FrmTest_SimpleBoard.xaml
    /// </summary>
    public partial class FrmTest_SimpleBoard : Window
    {
        public FrmTest_SimpleBoard()
        {
            InitializeComponent();
            initEvent();

            if (this.DataContext != null && this.DataContext is FrmTest_SimpleBoard_ViewModel viewModel)
            {
                viewModel.mOwner = this;
            }
        }

        void initEvent()
        {
            DataContextChanged += Frm_DataContextChanged;
            KeyUp += FrmTest_KeyUp;
            Closing += Frm_Closing;
            Closed += Frm_Closed;
        }

        private void FrmTest_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                this.Close();
            }
        }

        private void Frm_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.OldValue != null && e.OldValue is FrmTest_SimpleBoard_ViewModel oldViewModel)
            {
                oldViewModel.StopTimer();
            }
        }

        private void Frm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            var dr = WPFControls.MessageBox.ShowConfirmDialog(owner: this, "确认退出?"); // 阻塞等待返回结果
            if (dr != MessageBoxResult.OK)
            {
                e.Cancel = true;
            }
        }

        private void Frm_Closed(object sender, EventArgs e)
        {
            // 关闭窗口时需要停止 Timer, 不然会一直访问下去的
            (this.DataContext as FrmTest_SimpleBoard_ViewModel).StopTimer();
        }
    }

    public class FrmTest_SimpleBoard_ViewModel : BaseViewModel
    {
        public Window mOwner { get; set; }

        /// <summary>
        /// 每隔 x 秒更新数据
        /// </summary>
        public const int Wait = 30; // 30 秒

        public int mCurrent = 1; // 一开始获取一次数据

        public FrmTest_SimpleBoard_ViewModel()
        {
            initEvent();
            CheckServiceDateTime(); // 根据业务需求确认是否需要开启
        }

        void initEvent()
        {
            timer.Interval = 1000;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
        }

        #region 日期时间

        System.Timers.Timer timer { get; set; } = new System.Timers.Timer();

        private DateTime _CurrentDateTime = DateTime.Now;
        /// <summary>
        /// 当前日期时间
        /// </summary>
        public DateTime CurrentDateTime
        {
            get { return _CurrentDateTime; }
            set
            {
                _CurrentDateTime = value;
                this.OnPropertyChanged(nameof(CurrentDateTime));
                this.OnPropertyChanged(nameof(DateInfo));
                this.OnPropertyChanged(nameof(TimeInfo));
            }
        }

        public string DateInfo
        {
            get { return CurrentDateTime.ToString("yyyy-MM-dd"); }
        }

        public string TimeInfo
        {
            get { return CurrentDateTime.ToString("HH:mm:ss"); }
        }

        /// <summary>
        /// 校验服务器与本机时间的差异
        /// </summary>
        public void CheckServiceDateTime()
        {
            // Step 1 开启服务
            // DateTime serviceDateTime = webService.GetServiceDateTime(); // 从服务器获取网络时间
            DateTime serviceDateTime = DateTime.Now.AddMinutes(3); // 测试服务器时间校验
            DateTime now = DateTime.Now;

            TimeSpan tt = TimeSpan.FromTicks(Math.Abs(serviceDateTime.Ticks - now.Ticks)); // 计算时间差异

            if (tt >= TimeSpan.FromMinutes(3))
            {
                App.BeginInvokeOnMainThread(() =>
                {
                    var msg = $"本机时间与服务器时间差异大于3分钟, 请调整时间。\r\n本机时间: {now.ToString("yyyy-MM-dd HH:mm:ss")}\r\n服务器时间: {serviceDateTime.ToString("yyyy-MM-dd HH:mm:ss")}";
                    WPFControls.MessageBox.ShowWarningDialog(owner: mOwner, msg);
                });
            }
        }

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            updateClock();

            mCurrent = mCurrent - 1;
            if (mCurrent == 0)
            {
                try
                {
                    GetWorkshopKanBan_ActualData();
                }
                catch (Exception ex)
                {
                    // 这里是Timer的线程, 要回到主线程中显示捕获的异常信息
                    App.BeginInvokeOnMainThread(() =>
                    {
                        WPFControls.MessageBox.ShowError(owner: mOwner, exception: ex, autoCloseTimeSpan: TimeSpan.FromSeconds(Wait - 5));
                    });
                }
                finally
                {
                    mCurrent = Wait;
                }
            }
        }

        /// <summary>
        /// 更新时间
        /// </summary>
        void updateClock()
        {
            App.BeginInvokeOnMainThread(() =>
            {
                this.CurrentDateTime = DateTime.Now;
            });
        }

        public void StopTimer()
        {
            this.timer.Stop();
            this.timer.Elapsed -= Timer_Elapsed;
            this.timer = null;
        }

        #endregion

        private string _ShiftName;
        /// <summary>
        /// 班别
        /// </summary>
        public string ShiftName
        {
            get { return _ShiftName; }
            set
            {
                _ShiftName = value;
                this.OnPropertyChanged(nameof(ShiftName));
            }
        }


        // ============================= 各个项目自行实现 数据查询逻辑 =============================

        private List<Model> _List;
        public List<Model> List
        {
            get { return _List; }
            set
            {
                _List = value;
                this.OnPropertyChanged("List");
            }
        }

        Random rand = new Random();

        /// <summary>
        /// 从服务获取看板数据
        /// </summary>
        void GetWorkshopKanBan_ActualData()
        {
            int randCase = rand.Next(4);

            // if (randCase == 1 || randCase == 2)
            if (randCase == 1)
            {
                throw new Exception("抛出一个异常, 显示自动关闭窗口");
            }

            List<Model> l = new List<Model>();

            for (int i = 0; i < rand.Next(8, 50); i++)
            {
                // dynamic toAdd = new System.Dynamic.ExpandoObject();
                Model toAdd = new Model();
                l.Add(toAdd);

                toAdd.KPN = rand.Next(10000000, 100000000);
                toAdd.Customer = rand.Next(1000);
                toAdd.OrderQty = rand.Next(1000);
                toAdd.CartonQty = rand.Next(1000);
                toAdd.WorkingHours = rand.Next(1000);
                toAdd.Operator = rand.Next(1000);

                DateTime dtKaiban = DateTime.Now.AddMinutes(-rand.Next(30, 300));
                DateTime dtTouliao = dtKaiban.AddMinutes(rand.Next(30, 300));

                toAdd.KaiBanInfo = $"{dtKaiban.ToString("HH:mm")}";
                toAdd.TouLiaoInfo = $"{dtTouliao.ToString("HH:mm")}";


                int total = rand.Next(1000);
                int ScanQty = rand.Next(total);

                toAdd.Total = total;
                toAdd.CartonCountInfo = $"{ScanQty} / {total}";

                toAdd.Percentage0 = (int)((double)ScanQty / (double)total * 100d);
            }

            App.BeginInvokeOnMainThread(() =>
            {
                this.List = l;

                if (this.CurrentDateTime > this.CurrentDateTime.Date.AddHours(12))
                {
                    this.ShiftName = "午班";
                }
                else
                {
                    this.ShiftName = "早班";
                }
            });
        }

        public class Model
        {
            public int KPN { get; set; }
            public int Customer { get; set; }
            public int OrderQty { get; set; }
            public int CartonQty { get; set; }
            public int WorkingHours { get; set; }
            public int Operator { get; set; }
            public string KaiBanInfo { get; set; }
            public string TouLiaoInfo { get; set; }
            public int Total { get; set; }
            public string CartonCountInfo { get; set; }
            public int Percentage0 { get; set; }
        }
    }


}
